"""
@Time ： 2025/8/25 09:37
@Auth ： zh
@File ：material_price.py
"""
import requests

# 计算子清单库（汇总）列表的单价
def calculate_prices_from_api():
    # API地址
    test_url = "https://test.icii.agtsci.cn/api/cis/quota/subBill/library/listSubBill"
    prod_url = "https://icii.agt.cn/api/cis/quota/subBill/library/listSubBill"

    # 请求参数
    payload = {
        "name": "",
        "billName": "",
        "billDesc": "",
        "saveParam": "0",
        "orderFields": [],
        "type": "1",
        "quotaIds": [
            "7153932716810043392"
        ],
        "paramJsonStr": [
            "三龙湾数智科创产业园1#"
        ],
        "pageParamJson": {
            "quotaIds": [
                "7153932716810043392"
            ],
            "saveParam": "1",
            "paramJsonStr": [
                "三龙湾数智科创产业园1#"
            ]
        },
        "fileKindList": [],
        "regionIdList": [],
        "projectCategoryIds": [],
        "startTime": "",
        "endTime": "",
        "pageNumber": 1,
        "pageSize": 30
    }

    # 请求头
    headers = {
        "Authorization": "bearer 6eabcfc0-02da-4473-ab14-bae750a9a8ac",
        "Content-Type": "application/json"
    }

    try:
        # 发送POST请求
        response = requests.post(
            prod_url,
            json=payload,
            headers=headers,
            timeout=10
        )

        # 检查请求是否成功
        response.raise_for_status()

        # 解析JSON响应
        result = response.json()

        # 检查响应状态
        if result.get("code") != 200:
            print(f"API请求失败: {result.get('message', '未知错误')}")
            return []

        # 提取数据列表
        data_list = result.get("data", {}).get("list", [])
        if not data_list:
            print("没有找到数据列表")
            return []

        results = []

        # 遍历列表中的每个项目
        for index, item in enumerate(data_list):
            try:
                # 提取相关字段，使用get方法确保灵活性，不存在时返回0
                artificial_price = item.get("artificialPrice", 0)
                main_resource_price = item.get("mainResourcePrice", 0)

                # 辅材率：API返回的是百分比数值（如3表示3%），需要转换为小数
                auxiliary_ratio = item.get("auxiliaryResourceRatio", 0) / 100
                mechanical_price = item.get("mechanicalPrice", 0)

                # 管理费率：API返回的是百分比数值，转换为小数
                manage_rate = item.get("managePriceRate", 0) / 100

                # 利润率：API返回的是百分比数值，转换为小数
                profit_rate = item.get("profitRate", 0) / 100

                # 计算各项费用
                material_cost = main_resource_price + (main_resource_price * auxiliary_ratio)
                management_fee = (artificial_price + material_cost + mechanical_price) * manage_rate
                profit = (artificial_price + material_cost + mechanical_price + management_fee) * profit_rate
                unit_price = artificial_price + material_cost + mechanical_price + management_fee + profit

                # 整理结果，包含更多识别信息
                result_item = {
                    "序号": index + 1,
                    "子清单名称": item.get("billName", "未知项目"),
                    "定额编码": item.get("code", "无编码"),
                    "单位": item.get("unit", "无单位"),
                    "人工": round(artificial_price, 2),
                    "主材": round(main_resource_price, 2),
                    "辅材率": f"{item.get('auxiliaryResourceRatio', 0)}%",  # 显示为百分比
                    "辅材率(小数)": round(auxiliary_ratio, 4),  # 显示转换后的小数
                    "材料费": round(material_cost, 2),
                    "机具": round(mechanical_price, 2),
                    "管理费率": f"{item.get('managePriceRate', 0)}%",  # 显示为百分比
                    "管理费率(小数)": round(manage_rate, 4),  # 显示转换后的小数
                    "管理费": round(management_fee, 2),
                    "利润率": f"{item.get('profitRate', 0)}%",  # 显示为百分比
                    "利润率(小数)": round(profit_rate, 4),  # 显示转换后的小数
                    "利润": round(profit, 2),
                    "计算单价": round(unit_price, 2),
                    "原始单价": item.get("price", 0)
                }

                results.append(result_item)

            except Exception as e:
                print(f"处理第{index + 1}个项目时出错: {str(e)}")
                continue

        print(f"成功处理 {len(results)}/{len(data_list)} 个项目")
        return results

    except requests.exceptions.RequestException as e:
        print(f"请求发生错误: {str(e)}")
        return []
    except Exception as e:
        print(f"处理响应时发生错误: {str(e)}")
        return []


if __name__ == "__main__":
    # 从API获取并计算价格
    calculation_results = calculate_prices_from_api()

    # 打印结果
    if calculation_results:
        for result in calculation_results:
            print(f"\n项目: {result['子清单名称']} (编码: {result['定额编码']})")
            print(f"单位: {result['单位']}")
            print(f"人工: {result['人工']}")
            print(f"主材: {result['主材']}")
            print(f"辅材率: {result['辅材率']} (计算时使用: {result['辅材率(小数)']})")
            print(f"材料费: {result['材料费']}")
            print(f"机具: {result['机具']}")
            print(f"管理费率: {result['管理费率']} (计算时使用: {result['管理费率(小数)']})")
            print(f"管理费: {result['管理费']}")
            print(f"利润率: {result['利润率']} (计算时使用: {result['利润率(小数)']})")
            print(f"利润: {result['利润']}")
            print("计算公式为:",result['人工'],"+", result['材料费'],"+", result['机具'],"+", result['管理费'],"+", result['利润'])
            print(f"计算得出的单价: {result['计算单价']}")
            print(f"原始单价: {result['原始单价']}")
            print("-" * 80)
